﻿using System;
using System.Diagnostics;
using System.IO;
using System.Web;
using System.Web.Http;
using ELearning.Common.CommonStr;
using ELearning.Common.Helpers;
using ELearning.Common.Model;
using ELearning.Models.ViewModel.Upload;

namespace SiteAPI.Controllers.Common
{
    /// <summary>
    /// 上传文件控制器
    /// </summary>
    public class UploadController : BaseApiController
    {
        /// <summary>
        /// 上传附件到项目根目录下面
        /// </summary>
        [HttpPost, Route("api/Upload/UploadAttachment")]
        [AllowAnonymous]
        public ServiceResponse<UploadRespModel> UploadAttachment()
        {
            var viewModel = new UploadRespModel();
            var code = 200;
            var msg = "上传失败!";

            var path = FileUploadConst.UploadPath; //@"\\172.16.10.130\Resource";
            var s = connectState(path, FileUploadConst.UserName, FileUploadConst.Password);

            if (s)
            {
                var filelist = HttpContext.Current.Request.Files;
                if (filelist.Count > 0)
                {
                    var file = filelist[0];
                    var fileName = file.FileName;
                    var blobName = FileHelper.GetSaveFolder(fileName);
                    path = $@"{path}\{blobName}\";

                    fileName = $"{DateTime.Now:yyyyMMddHHmmss}{fileName}";

                    //共享文件夹的目录
                    var theFolder = new DirectoryInfo(path);
                    var remotePath = theFolder.ToString();
                    Transport(file.InputStream, remotePath, fileName);

                    viewModel.SaveUrl = $"{blobName}/{fileName}";
                    viewModel.DownloadUrl = PictureHelper.GetFileFullPath(viewModel.SaveUrl);

                    msg = "上传成功";
                }
            }
            else
            {
                code = CommonConst.Code_OprateError;
                msg = "链接服务器失败";
            }

            return ServiceResponse<UploadRespModel>.SuccessResponse(msg, viewModel, code);
        }

        /// <summary>
        /// 连接远程共享文件夹
        /// </summary>
        /// <param name="path">远程共享文件夹的路径</param>
        /// <param name="userName">用户名</param>
        /// <param name="passWord">密码</param>
        private static bool connectState(string path, string userName, string passWord)
        {
            var flag = false;
            var proc = new Process();
            try
            {
                proc.StartInfo.FileName = "cmd.exe";
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardInput = true;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.Start();
                var dosLine = "net use " + path + " " + passWord + " /user:" + userName;
                WriteHelper.WriteFile($"dosLine:{dosLine}");
                proc.StandardInput.WriteLine(dosLine);
                proc.StandardInput.WriteLine("exit");
                while (!proc.HasExited)
                {
                    proc.WaitForExit(1000);
                }

                var errormsg = proc.StandardError.ReadToEnd();
                proc.StandardError.Close();
                WriteHelper.WriteFile($"errormsg:{errormsg}");
                if (string.IsNullOrEmpty(errormsg))
                {
                    flag = true;
                }
                else
                {
                    throw new Exception(errormsg);
                }
            }
            catch (Exception ex)
            {
                WriteHelper.WriteFile(ex);
                throw ex;
            }
            finally
            {
                proc.Close();
                proc.Dispose();
            }

            return flag;
        }

        /// <summary>
        /// 向远程文件夹保存本地内容，或者从远程文件夹下载文件到本地
        /// </summary>
        /// <param name="inFileStream">要保存的文件的路径，如果保存文件到共享文件夹，这个路径就是本地文件路径如：@"D:\1.avi"</param>
        /// <param name="dst">保存文件的路径，不含名称及扩展名</param>
        /// <param name="fileName">保存文件的名称以及扩展名</param>
        private static void Transport(Stream inFileStream, string dst, string fileName)
        {
            WriteHelper.WriteFile($"目录-Transport：{dst}");
            if (!Directory.Exists(dst))
            {
                Directory.CreateDirectory(dst);
            }

            dst = dst + fileName;

            if (!File.Exists(dst))
            {
                WriteHelper.WriteFile($"文件不存在，开始保存");
                var outFileStream = new FileStream(dst, FileMode.Create, FileAccess.Write);

                var buf = new byte[inFileStream.Length];

                int byteCount;

                while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
                {
                    outFileStream.Write(buf, 0, byteCount);
                }
                WriteHelper.WriteFile($"保存完成");
                inFileStream.Flush();

                inFileStream.Close();

                outFileStream.Flush();

                outFileStream.Close();
            }
        }

    }
}